import { Page } from "@/entity/Page";
import OmsOrder from "@/entity/OmsOrder";
import { ResponseResult } from "@/entity/ResponseResult";
import { AxiosError, AxiosResponse } from "axios";
import httpClient from "./http-client";
import { OmsOrderCreationParam } from "@/entity/OmsOrderCreationParam";
import { OmsOrderUpdateParam } from "@/entity/OmsOrderUpdateParam";
import { OrderQueryParam } from "@/entity/OrderQueryParam";
import store, { TOKEN_USER_ID } from "@/store";
import { db_orderItems, db_orders } from "@/database/order";
import { db_members } from "@/database/member";
import OmsOrderStatus from "@/entity/OmsOrderStatus";
import { db_addresses } from "@/database/address";
import OmsOrderType from "@/entity/OmsOrderType";
import { db_cartItems } from "@/database/cart";
import OmsCartItem from "@/entity/OmsCartItem";
import PmsProduct from "@/entity/PmsProduct";
import { db_product } from "@/database/product";
import OmsOrderItem from "@/entity/OmsOrderItem";
import OmsPaymentType from "@/entity/OmsPaymentType";

Date.prototype.Format = function (fmt: string) {
    const o: any = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds() //秒 
    };
    if (/(y+)/.test(fmt)) { //根据y的长度来截取年
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
    return fmt;
}

export class OrderService {
    baseUrl = "/api/v1.0/portal/order";

    public async page(no: number = 1, size: number = 10) {
        const userId = Number(store.getters[TOKEN_USER_ID]);
        const res = db_orders.filter(it => it.memberId == userId).filter((it, idx) => {
            return idx >= (no - 1) * size && idx < no * size;
        }).map(it => {
            it.items = db_orderItems.filter(it2 => it2.orderId == it.id)
            return it;
        });
        return Promise.resolve({
            "content": res,
            "pageable": {
                "sort": {
                    "empty": false,
                    "sorted": true,
                    "unsorted": false
                },
                "offset": 0,
                "pageNumber": no - 1,
                "pageSize": size,
                "unpaged": false,
                "paged": true
            },
            "totalElements": db_orders.length,
            "last": true,
            "totalPages": db_orders.length / size + 1,
            "size": 10,
            "number": no,
            "sort": {
                "empty": false,
                "sorted": true,
                "unsorted": false
            },
            "numberOfElements": res.length,
            "first": true,
            "empty": false
        });
        // // 前端从1开始计数，后端从0开始计数
        // no = no - 1;
        // return httpClient.get(`${this.baseUrl}?page=${no}&size=${size}`).then((res: AxiosResponse<ResponseResult<Page<OmsOrder>>>) => {
        //     if (res.data.data) {
        //         const page = res.data.data;
        //         // 前端从1开始计数，后端从0开始计数
        //         page.number = page.number + 1;
        //         return Promise.resolve(page);
        //     } else {
        //         throw "no data";
        //     }
        // });
    }

    public async query(queryParam: OrderQueryParam = {}) {
        const no = queryParam.page == null ? 1 : queryParam.page;
        const size = queryParam.size == null ? 10 : queryParam.size;

        const userId = Number(store.getters[TOKEN_USER_ID]);
        let res = [];
        if (queryParam.orderStatus != null) {
            console.log(queryParam.orderStatus);
            console.log(db_orders.filter(it => it.memberId == userId && it.orderStatus == queryParam.orderStatus));
            res = db_orders.filter(it => it.memberId == userId && it.orderStatus == queryParam.orderStatus).filter((it, idx) => {
                return idx >= (no - 1) * size && idx < no * size;
            }).map(it => {
                it.items = db_orderItems.filter(it2 => it2.orderId == it.id)
                return it;
            });
        } else {
            res = db_orders.filter(it => it.memberId == userId).filter((it, idx) => {
                return idx >= (no - 1) * size && idx < no * size;
            }).map(it => {
                it.items = db_orderItems.filter(it2 => it2.orderId == it.id)
                return it;
            });
        }
        return Promise.resolve({
            "content": res,
            "pageable": {
                "sort": {
                    "empty": false,
                    "sorted": true,
                    "unsorted": false
                },
                "offset": 0,
                "pageNumber": no - 1,
                "pageSize": size,
                "unpaged": false,
                "paged": true
            },
            "totalElements": db_orders.length,
            "last": true,
            "totalPages": db_orders.length / size + 1,
            "size": 10,
            "number": no,
            "sort": {
                "empty": false,
                "sorted": true,
                "unsorted": false
            },
            "numberOfElements": res.length,
            "first": true,
            "empty": false
        });
        // // 前端从1开始计数，后端从0开始计数
        // if (queryParam.page == null) {
        //     queryParam.page = 1;
        // }
        // queryParam.page = queryParam.page - 1;
        // if (queryParam.size == null) {
        //     queryParam.size = 10;
        // }

        // const body = {
        //     ...queryParam,
        // }

        // return httpClient.post(`${this.baseUrl}/query`, body).then((res: AxiosResponse<ResponseResult<Page<OmsOrder>>>) => {
        //     if (res.data.data) {
        //         const page = res.data.data;
        //         // 前端从1开始计数，后端从0开始计数
        //         page.number = page.number + 1;
        //         return Promise.resolve(page);
        //     } else {
        //         throw "no data";
        //     }
        // });
    }

    public async retrieve(id: number) {
        const order = db_orders.find(it => it.id == id);
        if (order == null) {
            return Promise.resolve(order);
        } else {
            order.items = db_orderItems.filter(it => it.orderId == order.id);
            return Promise.resolve(order);
        }

        // return httpClient.get(`${this.baseUrl}/${id}`).then((res: AxiosResponse<ResponseResult<OmsOrder>>) => {
        //     if (res.data.data) {
        //         const p = res.data.data;
        //         return Promise.resolve(p);
        //     } else {
        //         throw "no data";
        //     }
        // });
    }

    public async create(param: OmsOrderCreationParam) {
        const userId = Number(store.getters[TOKEN_USER_ID]);

        let cartItems: OmsCartItem[] = [];
        let products: PmsProduct[] = [];
        if (param.orderType == OmsOrderType.DIRECTLY) {
            if (param.cartItems == null) {
                throw new AxiosError("商品不能为空");
            }
            cartItems = param.cartItems.map(it => {
                const e = new OmsCartItem();
                e.productId = it.productId;
                e.quantity = it.quantity;
                return e;
            });
            products = db_product.filter(it => cartItems.map(it2 => it2.productId).includes(it.id));
        } else {
            cartItems = db_cartItems.filter(it => param.cartItemIds?.includes(it.id));
            products = db_product.filter(it => cartItems.map(it2 => it2.productId).includes(it.id));
        }

        const user = db_members.find(it => it.id == userId);
        if (user == null) {
            throw new AxiosError("找不到下单用户");
        }

        const address = db_addresses.find(it => it.id == param.addressId);
        if (address == null) {
            throw new AxiosError("找不到地址信息");
        }

        const order = new OmsOrder();
        order.id = Math.max(...db_orders.map(it => it.id)) + 1;
        order.memberId = userId;
        order.amount = 0;
        order.code = "XSDD" + order.id;
        order.memberNickname = user.nickname;
        order.orderStatus = OmsOrderStatus.UNPAID;
        order.receiverAddress = address.receiverAddress;
        order.receiverCity = address.receiverCity;
        order.receiverCityCode = address.receiverCityCode;
        order.receiverDistrict = address.receiverDistrict;
        order.receiverDistrictCode = address.receiverDistrictCode;
        order.receiverName = address.receiverName;
        order.receiverPhone = address.receiverPhone;
        order.receiverProvince = address.receiverProvince;
        order.receiverProvinceCode = address.receiverProvinceCode;
        order.orderTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
        order.createdTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
        order.items = [];

        let amount = 0;
        let newId = Math.max(...db_orderItems.map(it => it.id)) + 1;
        const orderItems: OmsOrderItem[] = [];
        cartItems.forEach(it => {
            if (it.quantity == null) {
                throw new AxiosError("数量不能为空");
            }
            const product = products.find(it2 => it.productId == it2.id);
            if (product == null) {
                throw new AxiosError("找不到商品");
            }
            if (product.price == null) {
                throw new AxiosError("商品价格不能为空");
            }
            const item = new OmsOrderItem();
            item.id = (newId++);
            item.orderId = order.id;
            item.productId = product.id;
            item.productImgUrl = product.imgUrl;
            item.productName = product.name;
            item.quantity = it.quantity;
            item.price = it.price == null ? product.price : it.price;

            amount += (item.price * item.quantity);

            orderItems.push(item);
        });

        order.amount = amount;
        order.items = orderItems;

        db_orderItems.push(...orderItems);
        db_orders.push(order);
        if (param.orderType == OmsOrderType.FROM_CART) {
            const tmp = db_cartItems.filter(it => !cartItems.map(it2 => it2.id).includes(it.id));
            db_cartItems.length = 0;
            db_cartItems.push(...tmp);
        }

        return Promise.resolve(order.id);

        // const body = {
        //     ...param
        // }
        // return httpClient.post(`${this.baseUrl}`, body).then((res: AxiosResponse<ResponseResult<number>>) => {
        //     return Promise.resolve(res.data.data);
        // });
    }

    public async update(param: OmsOrderUpdateParam) {
        const order = db_orders.find(it => it.id == param.id);
        if (order == null) {
            throw new AxiosError("找不到订单");
        } else {
            order.orderStatus = param.orderStatus;
            if (order.orderStatus == OmsOrderStatus.CLOSED) {
                order.closedTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
            } else if (order.orderStatus == OmsOrderStatus.UN_EXPRESSED) {
                order.paymentType = OmsPaymentType.WECHAT;
                order.paymentTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
            }
            order.lastModifiedTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
        }
        return Promise.resolve({ "code": 200, "message": "操作成功", "data": order.id });

        // const body = {
        //     ...param
        // }
        // return httpClient.put(`${this.baseUrl}`, body).then((res: AxiosResponse<ResponseResult<number>>) => {
        //     return Promise.resolve(res.data.data);
        // });
    }
}

const instance = new OrderService();
export default instance;